<template>
     <div id="app" class="login_container" @keydown.enter="login">
          <!-- <el-row> -->
          <!-- <el-col :span="8" :xs="0"></el-col> -->
          <!-- <el-col :span="8" :xs="24"> -->
          <!-- 登录的表单 -->
          <el-form class="login_form" :model="loginForm" :rules="rules" ref="loginForms">
               <h1>Hello</h1>
               <h2>
                    欢迎登录
                    <span>{{ setting.title }}</span>
               </h2>
               <el-form-item prop="username">
                    <el-input :prefix-icon="User" v-model="loginForm.username" clearable></el-input>
               </el-form-item>
               <el-form-item prop="password">
                    <el-input type="password" :prefix-icon="Lock" v-model="loginForm.password" show-password clearable></el-input>
               </el-form-item>
               <el-form-item prop="verifycode">
                    <el-input v-model="loginForm.verifycode" autocomplete="off" :maxlength="4" placeholder="请输入验证码">
                         <template #prepend style="padding: 0 !important">
                              <ImgVerify @click="refashCode" v-if="ImgVerifyShow" :width="150" :height="40" :pool="pollCode"></ImgVerify>
                         </template>
                         <template #suffix>
                              <el-icon color="green" v-if="loginForm.verifycode && isVerifycode">
                                   <circle-check />
                              </el-icon>
                              <el-icon color="red" v-if="loginForm.verifycode && !isVerifycode">
                                   <circle-close />
                              </el-icon>
                         </template>
                    </el-input>
               </el-form-item>
               <el-form-item>
                    <el-button :loading="loading" class="login_btn" type="primary" size="default" @click="login">登录</el-button>
               </el-form-item>
          </el-form>
          <!-- </el-col> -->
          <!-- </el-row> -->
          <vue-particles id="tsparticles" :particlesInit="particlesInit" :particlesLoaded="particlesLoaded" :options="options" />
     </div>
</template>

<script setup lang="ts">
// @ts-ignore
import { loadSlim } from 'tsparticles-slim'
import { User, Lock } from '@element-plus/icons-vue'
// import { reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElNotification } from 'element-plus'
//引入获取当前时间的函数
import { getTime } from '@/utils/time'
//引入用户相关的小仓库
import useUserStore from '@/store/modules/user'
// @ts-ignore
import ImgVerify from '@/components/ImgVerify/index.vue'
import setting from '../../setting'
let useStore = useUserStore()
//获取路由器
let $router = useRouter()
//路由对象
let $route = useRoute()
//定义变量控制按钮加载效果
let loading = ref(false)
// 判断是否开发环境
const isDev = process.env.NODE_ENV === 'development'
//收集账号与密码的数据
let loginForm = reactive({
     username: isDev ? 'ma' : '',
     password: isDev ? 'crdc*2024' : '',
     verifycode: '',
})
const isVerifycode = computed(() => {
     //判断验证码是否正确
     return pollCode.value == loginForm.verifycode
})
const ImgVerifyShow = ref(true)
const pollCode = ref<number | string>('')
onMounted(async () => {
     refashCode()
})
const refashCode = async () => {
     //
     useStore.getVerifyCode()
     pollCode.value = useStore.verifyCodes.toString()
     ImgVerifyShow.value = false
     nextTick(() => {
          ImgVerifyShow.value = true
     })
}
//获取el-form组件
let loginForms = ref()
//登录按钮回调
const login = () => {
     console.log('login')
     if (!isVerifycode.value) {
          return ElNotification({
               type: 'error',
               message: '验证码错误',
               title: '验证码错误',
          })
     }
     loginForms.value &&
          loginForms.value.validate(async (valid: any) => {
               if (valid) {
                    try {
                         loading.value = true
                         //保证登录成功
                         let obj = {
                              username: loginForm.username,
                              password: loginForm.password,
                         }
                         await useStore.userLogin(obj)
                         //编程式导航跳转到展示数据首页
                         //判断登录的时候,路由路径当中是否有query参数，如果有就往query参数挑战，没有跳转到首页
                         let redirect: any = $route.query.redirect
                         $router.push({ path: '/' })
                         //登录成功提示信息
                         ElNotification({
                              type: 'success',
                              message: '欢迎回来',
                              title: `HI,${getTime()}好`,
                         })
                         //登录成功加载效果也消失
                         loading.value = false
                    } catch (error) {
                         refashCode()
                         //登录失败加载效果消息
                         loading.value = false
                         //登录失败的提示信息
                         ElNotification({
                              type: 'error',
                              message: (error as Error).message,
                         })
                    }
               } else {
                    console.log('error submit!')
               }
          })
}
// @ts-ignore
//自定义校验规则函数
const validatorUserName = (rule: any, value: any, callback: any) => {
     if (value.length >= 2) {
          callback()
     } else {
          callback(new Error('账号长度至少三位'))
     }
}
// @ts-ignore
const validatorPassword = (rule: any, value: any, callback: any) => {
     if (value.length >= 6) {
          callback()
     } else {
          callback(new Error('密码长度至少六位'))
     }
}

//定义表单校验需要配置对象
const rules = {
     username: [{ trigger: 'change', validator: validatorUserName }],
     password: [{ trigger: 'change', validator: validatorPassword }],
     verifycode: [
          {
               required: true,
               min: 4,
               max: 4,
               message: '请输入验证码,长度为4位',
               trigger: 'change',
          },
     ],
}

const particlesInit = async (engine: any) => {
     //await loadFull(engine);
     await loadSlim(engine)
}
const particlesLoaded = async (container: any) => {
     // console.log('Particles container loaded', container)
}

let options = {
     fpsLimit: 60,
     particles: {
          move: {
               bounce: false,
               direction: 'none',
               enable: true,
               outModes: 'out',
               random: false,
               speed: 2,
               straight: false,
          },
          number: { density: { enable: true, area: 800 }, value: 80 },
          opacity: {
               value: 0.5,
          },
          shape: {
               type: 'circle',
          },
          size: {
               value: { min: 1, max: 7 },
          },
     },
     // 主题样式
     themes: [
          {
               name: 'light',
               default: {
                    value: true,
                    mode: 'light',
               },
               options: {
                    background: {
                         color: '#243b55',
                    },
                    particles: {
                         color: {
                              value: ['#3998D0', '#2EB6AF', '#A9BD33', '#FEC73B', '#F89930', '#F45623', '#D62E32', '#EB586E', '#9952CF'],
                         },
                    },
               },
          },
          {
               name: 'dark',
               default: {
                    value: true,
                    mode: 'dark',
               },
               options: {
                    background: {
                         color: '#243b55',
                    },
                    particles: {
                         color: {
                              // 颜色
                              value: ['#3998D0', '#2EB6AF', '#A9BD33', '#FEC73B', '#F89930', '#F45623', '#D62E32', '#EB586E', '#9952CF'],
                         },
                    },
               },
          },
     ],
}
</script>
<style scoped lang="scss">
.login_container {
     width: 100%;
     height: 100vh;
     // background: linear-gradient(#141e30, rgba($color: #243b55, $alpha: .3));
     // color: rgba($color: #000000, $alpha: 1.0);
     display: flex;
     justify-content: center;
     align-items: center;
     background: url('@/assets/images/login/login_bg1.png') no-repeat;
     background-size: 100% 100%;

     .login_form {
          position: relative;
          width: 600px;
          // transform: translateX(-50%);
          background-size: cover;
          padding: 40px;
          overflow: hidden;
          background: #153374;
          border-radius: 15px;
          box-shadow:
               2px 2px 10px rgba(0, 0, 0, 0.2),
               -2px -2px 10px rgba(0, 0, 0, 0.2);

          h1 {
               color: #fff;
               font-size: 40px;
          }

          h2 {
               font-size: 20px;
               color: #fff;
               margin: 20px 0px;

               span {
                    font-size: 25px;
                    font-weight: bold;
               }
          }

          .login_btn {
               width: 100%;
          }
     }

     // .login_form::before {
     //      content: ' ';
     //      position: absolute;
     //      background: inherit;
     //      width: 100%;
     //      height: 100%;
     //      left: 0;
     //      top: 0;
     //      box-shadow: inset 0 0 0 200px rgba(0, 0, 0, .8);
     //      filter: blur(10px);
     // }
}

#tsparticles {
     z-index: -1;
     // background: linear-gradient(#141e30, rgba($color: #243b55, $alpha: .3));
}

::v-deep(.el-input-group__prepend) {
     padding: 0;
}
</style>
